#!/bin/sh

set -eu

setup_user () {
    # Sets up the stork-server user and its home directory.
    if ! getent passwd stork-server > /dev/null; then
        adduser --quiet --system --group --home /var/lib/stork-server \
            --no-create-home --disabled-password --disabled-login \
            --gecos "Stork Server User" stork-server >/dev/null
    fi
}

after_install () {
    setup_user
}

after_upgrade () {
    # Prior Stork 1.16.0 the update case was not specifically handled. The
    # postrm script deleted the user and the postinst recreated it.
    # The user is preserved during the upgrade if the version is 1.16.0 or
    # higher. For the older versions, the user must be recreated.
    setup_user

    # Check if the systemd is available.
    has_active_systemd=0
    if command -v systemctl > /dev/null; then
        status=$(systemctl is-system-running || true)
        if [ "${status}" = "running" ] || [ "${status}" = "degraded" ] || [ "${status}" = "maintenance" ]; then
            has_active_systemd=1
        fi
    fi

    # Restart the systemd service.
    if [ $has_active_systemd -eq 1 ]; then
        is_active_service=$(systemctl is-active isc-stork-server || true)
        if [ "${is_active_service}" = "active" ]; then
            systemctl restart isc-stork-server
        fi
    fi
}


if [ "${1}" = "abort-remove" ] || { [ "${1}" = "configure" ] && [ -z "${2}" ]; }
then
    # "after install" here
    # "abort-remove" happens when the pre-removal script failed.
    #   In that case, this script, which should be idemptoent, is run
    #   to ensure a clean roll-back of the removal.
    after_install
elif [ "${1}" = "configure" ] && [ -n "${2}" ]
then
    # "after upgrade" here
    # NOTE: This slot is also used when deb packages are removed,
    # but their config files aren't, but a newer version of the
    # package is installed later, called "Config-Files" state.
    # Basically, that still looks a _lot_ like an upgrade to me.
    after_upgrade "${2}"
elif echo "${1}" | grep -E -q "(abort|fail)"
then
    echo "Failed to install before the post-installation script was run." >&2
    exit 1
fi
